#include <stddef.h>
#include <GL/glew.h>
#include "../Core/Assert.h"
#include "IndexBuffer.h"


IndexBuffer::IndexBuffer(Usage usage, IndexType indexType, size_t indexCount)
    : type(indexType)
    , count(indexCount)
{
    GLenum glUsage = GL_STATIC_DRAW;
    switch (usage)
    {
    case kStatic: glUsage = GL_STATIC_DRAW; break;
    case kStreaming: glUsage = GL_STREAM_DRAW; break;
    case kDynamic: glUsage = GL_DYNAMIC_DRAW; break;
    default: Fatal("Invalid usage");
    }

    glGenBuffers(1, &handle);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, handle);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexType*indexCount, NULL, glUsage);
}

IndexBuffer::~IndexBuffer()
{
    glDeleteBuffers(1, &handle);
}

IndexBuffer::IndexType IndexBuffer::GetIndexType() const
{
    return type;
}

size_t IndexBuffer::GetIndexCount() const
{
    return count;
}

void BindIndexBuffer(const IndexBuffer* buffer)
{
    if (NULL != buffer)
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer->GetHandle());
    else
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}

void SetIndexData(const IndexBuffer* buffer, const void* indexData, size_t indexOffset, size_t indexCount)
{
    size_t stride = buffer->GetIndexType();
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer->GetHandle());
    glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, indexOffset*stride, indexCount*stride, indexData);
}
